<template>
  <div class="signature-container">
    <!-- 顶部导航 -->
    <header class="header">
      <div class="header-content">
        <i class="el-icon-arrow-left" @click="goBack"></i>
        <h1>电子签名</h1>
        <span class="save-btn" @click="saveSignature">保存</span>
      </div>
    </header>

    <!-- 签名区域 -->
    <div class="signature-section">
      <div class="canvas-container">
        <canvas 
          ref="signatureCanvas" 
          class="signature-canvas"
          @mousedown="startDrawing"
          @mousemove="draw"
          @mouseup="stopDrawing"
          @mouseout="stopDrawing"
          @touchstart="handleTouchStart"
          @touchmove="handleTouchMove"
          @touchend="handleTouchEnd"
        ></canvas>
        <div v-if="!hasSignature" class="placeholder">
          <i class="el-icon-edit"></i>
          <p>请在此处签名</p>
        </div>
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="tool-group">
        <div class="tool-item" @click="clearCanvas">
          <i class="el-icon-delete"></i>
          <span>清除</span>
        </div>
        <div class="tool-item" @click="undo">
          <i class="el-icon-refresh-left"></i>
          <span>撤销</span>
        </div>
        <div class="tool-item" @click="changePenColor">
          <div class="color-preview" :style="{ backgroundColor: penColor }"></div>
          <span>颜色</span>
        </div>
        <div class="tool-item pen-size">
          <i class="el-icon-minus" @click="decreasePenSize"></i>
          <span class="size-value">{{ penSize }}px</span>
          <i class="el-icon-plus" @click="increasePenSize"></i>
        </div>
      </div>
    </div>

    <!-- 颜色选择器 -->
    <div v-if="showColorPicker" class="color-picker">
      <div 
        v-for="color in colorOptions" 
        :key="color"
        class="color-option"
        :style="{ backgroundColor: color }"
        @click="selectColor(color)"
      ></div>
    </div>

    <!-- 保存预览弹窗 -->
    <el-dialog
      :visible.sync="showPreview"
      title="签名预览"
      width="90%"
      center
    >
      <div class="preview-container">
        <img v-if="signatureImage" :src="signatureImage" class="signature-preview" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showPreview = false">取消</el-button>
        <el-button type="primary" @click="downloadSignature">下载图片</el-button>
      </div>
    </el-dialog>

    
  </div>
</template>

<script>
export default {
  name: 'SignaturePad',
  data() {
    return {
      canvas: null,
      ctx: null,
      isDrawing: false,
      lastX: 0,
      lastY: 0,
      penColor: '#000000',
      penSize: 3,
      hasSignature: false,
      showColorPicker: false,
      showPreview: false,
      signatureImage: '',
      colorOptions: [
        '#000000', '#FF0000', '#0000FF', '#008000', 
        '#FFA500', '#800080', '#FFC0CB', '#A52A2A'
      ],
      drawingHistory: [],

    }
  },
  mounted() {
    this.initCanvas()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    initCanvas() {
      this.canvas = this.$refs.signatureCanvas
      this.ctx = this.canvas.getContext('2d')
      this.resizeCanvas()
      this.setupCanvas()
    },
    setupCanvas() {
      this.ctx.lineCap = 'round'
      this.ctx.lineJoin = 'round'
      this.ctx.strokeStyle = this.penColor
      this.ctx.lineWidth = this.penSize
    },
    resizeCanvas() {
      const container = this.canvas.parentElement
      const rect = container.getBoundingClientRect()
      
      this.canvas.width = rect.width * window.devicePixelRatio
      this.canvas.height = rect.height * window.devicePixelRatio
      
      this.canvas.style.width = rect.width + 'px'
      this.canvas.style.height = rect.height + 'px'
      
      this.ctx.scale(window.devicePixelRatio, window.devicePixelRatio)
    },
    handleResize() {
      this.resizeCanvas()
      this.setupCanvas()
    },
    getCoordinates(event) {
      const rect = this.canvas.getBoundingClientRect()
      return {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
      }
    },
    getTouchCoordinates(event) {
      const rect = this.canvas.getBoundingClientRect()
      const touch = event.touches[0] || event.changedTouches[0]
      return {
        x: touch.clientX - rect.left,
        y: touch.clientY - rect.top
      }
    },
    startDrawing(event) {
      this.isDrawing = true
      const coords = this.getCoordinates(event)
      this.lastX = coords.x
      this.lastY = coords.y
      
      this.ctx.beginPath()
      this.ctx.moveTo(this.lastX, this.lastY)
    },
    draw(event) {
      if (!this.isDrawing) return
      
      const coords = this.getCoordinates(event)
      
      this.ctx.beginPath()
      this.ctx.moveTo(this.lastX, this.lastY)
      this.ctx.lineTo(coords.x, coords.y)
      this.ctx.stroke()
      
      this.lastX = coords.x
      this.lastY = coords.y
      
      this.hasSignature = true
    },
    stopDrawing() {
      this.isDrawing = false
      if (this.hasSignature) {
        this.saveDrawingState()
      }
    },
    handleTouchStart(event) {
      event.preventDefault()
      const coords = this.getTouchCoordinates(event)
      this.startDrawing({
        clientX: coords.x + this.canvas.getBoundingClientRect().left,
        clientY: coords.y + this.canvas.getBoundingClientRect().top
      })
    },
    handleTouchMove(event) {
      event.preventDefault()
      const coords = this.getTouchCoordinates(event)
      this.draw({
        clientX: coords.x + this.canvas.getBoundingClientRect().left,
        clientY: coords.y + this.canvas.getBoundingClientRect().top
      })
    },
    handleTouchEnd(event) {
      event.preventDefault()
      this.stopDrawing()
    },
    saveDrawingState() {
      this.drawingHistory.push(this.canvas.toDataURL())
      if (this.drawingHistory.length > 50) {
        this.drawingHistory.shift()
      }
    },
    clearCanvas() {
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
      this.hasSignature = false
      this.drawingHistory = []
      this.displayMessage('签名已清除')
    },
    undo() {
      if (this.drawingHistory.length > 0) {
        this.drawingHistory.pop()
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
        
        if (this.drawingHistory.length > 0) {
          const img = new Image()
          img.onload = () => {
            this.ctx.drawImage(img, 0, 0)
          }
          img.src = this.drawingHistory[this.drawingHistory.length - 1]
        } else {
          this.hasSignature = false
        }
      }
    },
    changePenColor() {
      this.showColorPicker = !this.showColorPicker
    },
    selectColor(color) {
      this.penColor = color
      this.ctx.strokeStyle = color
      this.showColorPicker = false
    },
    increasePenSize() {
      if (this.penSize < 10) {
        this.penSize += 1
        this.ctx.lineWidth = this.penSize
      }
    },
    decreasePenSize() {
      if (this.penSize > 1) {
        this.penSize -= 1
        this.ctx.lineWidth = this.penSize
      }
    },
    saveSignature() {
      if (!this.hasSignature) {
        this.displayMessage('请先签名', 'warning')
        return
      }
      
      this.signatureImage = this.canvas.toDataURL('image/png')
      this.showPreview = true
    },
    downloadSignature() {
      const link = document.createElement('a')
      link.download = `signature_${new Date().getTime()}.png`
      link.href = this.signatureImage
      link.click()
      this.showPreview = false
      this.displayMessage('签名已保存')
    },
    goBack() {
      this.$router.go(-1)
    },
    displayMessage(text, type = 'success') {
      this.$message({
        message: text,
        type: type,
        center: true
      })
    }
  }
}
</script>

<style scoped>
.signature-container {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.header {
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
}

.header-content i {
  font-size: 20px;
  cursor: pointer;
  color: #333;
}

.header-content h1 {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin: 0;
}

.save-btn {
  color: #409EFF;
  font-size: 16px;
  cursor: pointer;
  font-weight: 500;
}

.signature-section {
  flex: 1;
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.canvas-container {
  position: relative;
  width: 100%;
  max-width: 400px;
  height: 300px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  overflow: hidden;
}

.signature-canvas {
  width: 100%;
  height: 100%;
  cursor: crosshair;
  display: block;
}

.placeholder {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #999;
  pointer-events: none;
}

.placeholder i {
  font-size: 48px;
  margin-bottom: 8px;
}

.placeholder p {
  font-size: 16px;
  margin: 0;
}

.toolbar {
  background: white;
  padding: 16px;
  box-shadow: 0 -2px 8px rgba(0,0,0,0.1);
}

.tool-group {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.tool-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: background-color 0.3s;
}

.tool-item:hover {
  background: #f5f5f5;
}

.tool-item i {
  font-size: 24px;
  color: #666;
  margin-bottom: 4px;
}

.tool-item span {
  font-size: 12px;
  color: #666;
}

.color-preview {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  border: 2px solid #ddd;
  margin-bottom: 4px;
}

.pen-size {
  flex-direction: row;
  gap: 8px;
}

.pen-size i {
  margin: 0;
}

.size-value {
  font-size: 12px;
  color: #666;
  min-width: 30px;
  text-align: center;
}

.color-picker {
  position: absolute;
  bottom: 100px;
  left: 50%;
  transform: translateX(-50%);
  background: white;
  padding: 12px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  display: flex;
  gap: 8px;
  z-index: 200;
}

.color-option {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  cursor: pointer;
  border: 2px solid #ddd;
  transition: transform 0.2s;
}

.color-option:hover {
  transform: scale(1.1);
}

.preview-container {
  text-align: center;
}

.signature-preview {
  max-width: 100%;
  max-height: 300px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.dialog-footer {
  text-align: center;
}

@media (max-width: 768px) {
  .canvas-container {
    height: 250px;
  }
  
  .tool-group {
    gap: 8px;
  }
  
  .tool-item span {
    font-size: 11px;
  }
}
</style>